<template>
  <div
    class="app-wrapper"
    :class="{ mobile: isMobile, horizontal: isHorizontal }"
  >
    <!-- 遮罩层 -->
    <div
      v-if="isMobile && !isCollapse"
      class="drawer-bg"
      @click="closeSidebar"
    />

    <!-- 侧边栏 - 垂直布局时显示 -->
    <div
      v-if="!isHorizontal"
      class="sidebar-container"
      :class="{ collapse: isCollapse }"
    >
      <div class="logo-container">
        <img src="@/assets/vue.svg" alt="logo" class="logo-img" />
        <h1 class="logo-title" v-show="!isCollapse">Vue Admin</h1>
      </div>

      <el-scrollbar>
        <el-menu
          :default-active="activeMenu"
          :collapse="isCollapse"
          :unique-opened="true"
          :background-color="
            themeStore.config.theme === 'dark'
              ? '#1a1a1a'
              : themeStore.config.sidebarColor
          "
          :text-color="
            themeStore.config.theme === 'dark'
              ? '#a3a6ad'
              : themeStore.config.menuTextColor
          "
          :active-text-color="themeStore.config.menuActiveTextColor"
          router
          class="el-menu-vertical"
        >
          <template
            v-for="route in permissionStore.menuRoutes"
            :key="route.path"
          >
            <sidebar-item
              :menu="route"
              :base-path="route.path === 'dashboard' ? '' : route.path"
            />
          </template>
        </el-menu>
      </el-scrollbar>
    </div>

    <!-- 主容器 -->
    <div class="main-container">
      <!-- 顶部导航栏 -->
      <div class="navbar" :class="{ 'horizontal-navbar': isHorizontal }">
        <!-- 横向布局时显示logo和菜单 -->
        <template v-if="isHorizontal">
          <div class="logo-container">
            <img src="@/assets/vue.svg" alt="logo" class="logo-img" />
            <h1 class="logo-title">Vue Admin</h1>
          </div>

          <div class="menu-container">
            <el-menu
              :default-active="activeMenu"
              mode="horizontal"
              router
              class="horizontal-menu"
              :background-color="themeStore.config.sidebarColor"
              :text-color="themeStore.config.menuTextColor"
              :active-text-color="themeStore.config.menuActiveTextColor"
            >
              <sidebar-item
                v-for="route in routes"
                :key="route.path"
                :menu="route"
              />
            </el-menu>
          </div>
        </template>

        <!-- 垂直布局时显示折叠按钮和面包屑 -->
        <template v-else>
          <div class="navbar-left">
            <div class="hamburger" @click="toggleSidebar">
              <el-icon :size="20">
                <component :is="isCollapse ? 'Expand' : 'Fold'" />
              </el-icon>
            </div>
            <breadcrumb class="breadcrumb" />
          </div>
        </template>

        <!-- 用户信息区域 -->
        <div class="navbar-right">
          <el-dropdown trigger="click" @command="handleCommand">
            <div class="avatar-wrapper">
              <el-avatar
                :size="32"
                :src="userStore.userInfo?.avatar"
                class="user-avatar"
              />
              <span class="user-name">{{ userStore.userInfo?.nickname }}</span>
              <el-icon class="el-icon--right"><CaretBottom /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  <span>个人信息</span>
                </el-dropdown-item>
                <el-dropdown-item command="theme">
                  <el-icon><Setting /></el-icon>
                  <span>主题设置</span>
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  <span>退出登录</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 主要内容区 -->
      <div class="app-main">
        <router-view v-slot="{ Component }">
          <transition name="fade-transform" mode="out-in">
            <keep-alive>
              <component :is="Component" />
            </keep-alive>
          </transition>
        </router-view>
      </div>
    </div>

    <theme-drawer ref="themeDrawerRef" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  Fold,
  Expand,
  CaretBottom,
  User,
  SwitchButton,
  Setting,
} from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { useUserStore } from "@/store/user";
import SidebarItem from "./SidebarItem.vue";
import Breadcrumb from "./Breadcrumb.vue";
import ThemeDrawer from "./ThemeDrawer.vue";
import { useThemeStore } from "@/store/theme";
import { usePermissionStore } from "@/store/permission";

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const themeStore = useThemeStore();

const isCollapse = ref(false);
const isMobile = ref(false);
const activeMenu = computed(() => route.path);

// 获取路由
const permissionStore = usePermissionStore();
const routes = computed(() => permissionStore.menuRoutes);

const isHorizontal = computed(() => themeStore.config.layout === "horizontal");

// 切换侧边栏
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value;
};

// 响应式处理
const handleResize = () => {
  isMobile.value = window.innerWidth < 992;
  if (isMobile.value) {
    isCollapse.value = true;
  }
};

onMounted(() => {
  handleResize();
  window.addEventListener("resize", handleResize);
  themeStore.applyTheme();
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
});

// 用户操作
const handleCommand = async (command: string) => {
  if (command === "logout") {
    try {
      await ElMessageBox.confirm("确认退出登录吗？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      });
      await userStore.logout();
      router.push("/login");
    } catch {
      // 取消退出
    }
  } else if (command === "profile") {
    router.push("/profile");
  } else if (command === "theme") {
    themeDrawerRef.value?.open();
  }
};

// 添加关闭侧边栏方法
const closeSidebar = () => {
  isCollapse.value = true;
};

// 主题设置相关
const themeDrawerRef = ref();

const openThemeDrawer = () => {
  themeDrawerRef.value?.open();
};
</script>

<style lang="scss" scoped>
.app-wrapper {
  position: relative;
  height: 100%;
  width: 100%;
  display: flex;

  // 遮罩层
  .drawer-bg {
    background: #000;
    opacity: 0.3;
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    transition: opacity 0.3s;
  }

  // 侧边栏
  .sidebar-container {
    width: 220px;
    height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    bottom: 0;
    overflow: hidden;
    transition: all 0.3s;
    background: var(--sidebar-bg-color);
    z-index: 1001;

    &.collapse {
      width: 64px;

      .logo-title {
        display: none;
      }
    }

    .logo-container {
      height: 60px;
      padding: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0, 0, 0, 0.1);

      .logo-img {
        width: 32px;
        height: 32px;
      }

      .logo-title {
        margin-left: 12px;
        color: var(--menu-text-color);
        font-size: 18px;
        font-weight: 600;
        white-space: nowrap;
        overflow: hidden;
      }
    }

    .el-menu-vertical {
      border: none;
      height: calc(100% - 60px);
      background: transparent;

      :deep(.el-menu) {
        background-color: var(--menu-sub-bg-color) !important;
      }

      :deep(.el-menu-item),
      :deep(.el-sub-menu__title) {
        height: 50px !important;
        line-height: 50px !important;
        color: var(--menu-text-color) !important;

        &:hover {
          background-color: var(--menu-hover-bg-color) !important;
        }

        &.is-active {
          background-color: var(--menu-active-bg-color) !important;
          color: var(--menu-active-text-color) !important;
          border-right: 2px solid var(--menu-active-text-color) !important;

          &::after {
            display: none !important;
          }
        }
      }

      :deep(.el-sub-menu) {
        .el-menu {
          background-color: var(--menu-sub-bg-color) !important;

          .el-menu-item {
            padding-left: 52px !important;

            &.is-active {
              background-color: var(--menu-active-bg-color) !important;
            }
          }
        }
      }
    }
  }

  // 主容器
  .main-container {
    min-height: 100vh;
    flex: 1;
    margin-left: 220px;
    position: relative;
    background: var(--main-bg-color);
    transition: margin-left 0.3s;
    width: calc(100% - 220px);
    padding-top: 60px;

    .navbar {
      height: 60px;
      padding: 0 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: var(--navbar-bg-color);
      box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
      position: fixed;
      top: 0;
      right: 0;
      left: 220px;
      z-index: 1000;
      transition: left 0.3s;

      .navbar-left {
        display: flex;
        align-items: center;

        .hamburger {
          padding: 0 12px;
          cursor: pointer;
          transition: background 0.3s;
          border-radius: 4px;
          color: var(--el-text-color-primary);

          &:hover {
            background: var(--el-fill-color-light);
          }
        }

        .breadcrumb {
          margin-left: 8px;
          color: var(--el-text-color-primary);
        }
      }

      .navbar-right {
        display: flex;
        align-items: center;

        .avatar-wrapper {
          display: flex;
          align-items: center;
          padding: 0 8px;
          height: 40px;
          cursor: pointer;
          border-radius: 4px;
          transition: background 0.3s;
          color: var(--el-text-color-primary);

          &:hover {
            background: var(--el-fill-color-light);
          }

          .user-avatar {
            margin-right: 8px;
          }

          .user-name {
            font-size: 14px;
            color: var(--el-text-color-primary);
          }

          .el-icon--right {
            margin-left: 4px;
            color: var(--el-text-color-primary);
          }
        }
      }

      &.horizontal-navbar {
        padding: 0;
        height: 60px;
        display: flex;
        align-items: center;
        background: var(--sidebar-bg-color);

        .logo-container {
          width: 200px;
          height: 60px;
          padding: 0 20px;
          display: flex;
          align-items: center;
          border-right: 1px solid rgba(255, 255, 255, 0.05);

          .logo-img {
            width: 32px;
            height: 32px;
          }

          .logo-title {
            margin: 0 0 0 12px;
            color: #fff;
            font-size: 18px;
            font-weight: 600;
            white-space: nowrap;
          }
        }

        .menu-container {
          flex: 1;
          height: 60px;
          overflow: hidden;

          .horizontal-menu {
            border: none;
            height: 60px;
            line-height: 60px;
            width: 100%;
            display: flex;
            justify-content: flex-start;
            background: transparent;

            :deep(.el-menu--horizontal) {
              border: none;
              background: transparent;
            }

            :deep(.el-menu-item),
            :deep(.el-sub-menu__title) {
              height: 60px;
              line-height: 60px;
              color: var(--menu-text-color);
              background: transparent;

              &:hover,
              &:focus {
                background: rgba(255, 255, 255, 0.05);
              }

              &.is-active {
                color: var(--menu-active-text-color);
                background: var(--menu-active-bg-color);
                border-bottom: 2px solid var(--menu-active-text-color);
              }
            }
          }
        }

        .navbar-right {
          padding: 0 20px;
          height: 60px;
          display: flex;
          align-items: center;
          gap: 16px;

          .avatar-wrapper {
            color: var(--menu-text-color);

            .user-name {
              color: var(--menu-text-color);
            }

            &:hover {
              background: rgba(255, 255, 255, 0.05);
            }
          }
        }
      }
    }

    .app-main {
      padding: 20px;
      min-height: calc(100vh - 60px);
      box-sizing: border-box;
      overflow: auto;
      background: var(--main-bg-color);
    }
  }

  // 向布局样式
  &.horizontal {
    .main-container {
      margin-left: 0;
      width: 100%;
      padding-top: 60px;

      .navbar {
        left: 0;
      }

      .app-main {
        padding: 20px;
        min-height: calc(100vh - 60px);
      }
    }
  }

  // 移动端适配
  &.mobile {
    .sidebar-container {
      transform: translateX(v-bind('isCollapse ? "-220px" : "0"'));
      width: 220px !important;
    }

    .main-container {
      margin-left: 0 !important;
      width: 100% !important;

      .navbar {
        left: 0;
      }
    }

    .drawer-bg {
      display: block;
    }
  }

  // 非移动端折叠状态
  &:not(.mobile):not(.horizontal) {
    .main-container {
      margin-left: v-bind('isCollapse ? "64px" : "220px"');
      width: calc(100% - v-bind('isCollapse ? "64px" : "220px"'));

      .navbar {
        left: v-bind('isCollapse ? "64px" : "220px"');
      }
    }
  }
}

// 路由切换动画
.fade-transform-enter-active,
.fade-transform-leave-active {
  transition: all 0.3s;
}

.fade-transform-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.fade-transform-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

// 深色主题样式
:deep(html.dark) {
  .sidebar-container {
    background-color: var(--sidebar-bg-color) !important;

    .el-menu {
      background-color: var(--sidebar-bg-color) !important;

      .el-menu-item,
      .el-sub-menu__title {
        color: var(--menu-text-color) !important;
        background-color: transparent !important;

        &:hover {
          background-color: var(--menu-hover-bg-color) !important;
        }

        &.is-active {
          background-color: var(--menu-active-bg-color) !important;
          color: var(--menu-active-text-color) !important;
        }
      }

      .el-sub-menu {
        .el-menu {
          background-color: var(--menu-sub-bg-color) !important;
        }
      }
    }
  }

  .navbar {
    background-color: var(--navbar-bg-color) !important;
    border-bottom: 1px solid var(--el-border-color) !important;

    .hamburger {
      color: var(--el-text-color-primary) !important;

      &:hover {
        background-color: var(--el-fill-color-light) !important;
      }
    }

    .breadcrumb {
      :deep(.el-breadcrumb__inner) {
        color: var(--el-text-color-primary) !important;

        &:hover {
          color: var(--el-color-primary) !important;
        }

        &.no-redirect {
          color: var(--el-text-color-secondary) !important;
        }
      }
    }

    .avatar-wrapper {
      color: var(--el-text-color-primary) !important;

      &:hover {
        background-color: var(--el-fill-color-light) !important;
      }

      .user-name {
        color: var(--el-text-color-primary) !important;
      }

      .el-icon {
        color: var(--el-text-color-primary) !important;
      }
    }
  }
}

// 移动端适配
@media screen and (max-width: 768px) {
  .app-wrapper.horizontal {
    .horizontal-header {
      .logo-container {
        width: 60px;
        padding: 0 10px;

        .logo-title {
          display: none;
        }
      }

      .navbar-right {
        min-width: auto;
        padding: 0 10px;

        .user-name {
          display: none;
        }
      }
    }
  }
}
</style>
